<?php

namespace app\common\model;

use think\Model;
use think\model\concern\SoftDelete;

class Article extends Model
{
    //软删除
    use SoftDelete;

    //文章列表所属导航关联栏目表
    public function cate()
    {
        //多对一
        return $this->belongsTo('Cate','cate_id','id');
    }

    //关联评论
    public function comments()
    {
        //一对多
        return $this->hasMany('Comment','article_id','id');
    }

    //添加文章
    public function add($data)
    {
        //创建验证器
        $validate = new \app\common\validate\Article();
        if (!$validate->scene('add')->check($data)){
            return $validate->getError();
        }
        //只验证数据库里有的字段并赋值给result
        $result = $this->allowField(true)->save($data);
        if ($result){
            return 1;
        }else{
            return '添加失败';
        }
    }

    //推荐操作
    public function top($data)
    {
        //创建验证器
        $validate = new \app\common\validate\Article();
        //当数据没有通过验证
        if (!$validate->scene('top')->check($data)){
            return $validate->getError();
        }
        //查询出article的id赋值给articleInfo
        $articleInfo = $this->find($data['id']);
        //更新articleInfo
        $articleInfo->is_top = $data['is_top'];
        //将更新结果赋值给result
        $result = $articleInfo->save();
        if ($result){
            return 1;
        }else{
            return '操作失败';
        }
    }

    //文章编辑
    public function edit($data)
    {
        //创建验证器
        $validate = new \app\common\validate\Article();
        //当数据没有通过验证
        if (!$validate->scene('edit')->check($data)){
            return $validate->getError();
        }
        //查询出article的id赋值给articleInfo
        $articleInfo = $this->find($data['id']);
        //更新articleInfo
        $articleInfo->title = $data['title'];
        $articleInfo->tags = $data['tags'];
        $articleInfo->is_top = $data['is_top'];
        $articleInfo->cate_id = $data['cate_id'];
        $articleInfo->desc = $data['desc'];
        $articleInfo->content = $data['content'];
        //将更新结果赋值给result
        $result = $articleInfo->save();
        if ($result){
            return 1;
        }else{
            return '更新失败';
        }
    }
}
